<template>
  <div class="task-container">
    <TaskHeader
        :sidebar-collapsed="sidebarCollapsed"
        @toggle-sidebar="sidebarCollapsed = !sidebarCollapsed"
        @go-calendar="goCalendarPage"
        @go-task="goTaskPage"
        @show-user-menu="showUserMenu"
    />

    <div class="main-content">
      <TaskSidebar
          :sidebar-collapsed="sidebarCollapsed"
          :task-lists="taskLists"
          :active-list-index="activeListIndex"
          :is-task-list-open="isTaskListOpen"
          :show-new-list-dialog="showNewListDialog"
          @update:is-task-list-open="isTaskListOpen = $event"
          @update:show-new-list-dialog="showNewListDialog = $event"
          @create-new-task-list="createNewTaskList"
          @handle-category-click="handleCategoryClick"
          @handle-visibility-change="handleVisibilityChange"
          @add-new-task="addNewTask"
      />

      <TaskCardList
          ref="taskCardListRef"
          :task-lists="taskLists"
          :active-list-index="activeListIndex"
          :show-task-options="showTaskOptions"
          @update:show-task-options="showTaskOptions = $event"
          @toggle-task-options="toggleTaskOptions"
          @handle-card-click="handleCardClick"
          @add-task-to-list="addTaskToList"
          @start-editing-list-name="startEditingListName"
          @save-list-name="saveListName"
          @show-list-options-menu="showListOptionsMenu"
          @handle-task-complete="handleTaskComplete"
          @start-editing="startEditing"
          @save-editing="saveEditing"
          @handle-title-enter="handleTitleEnter"
          @navigate-to-desc="navigateToDesc"
          @navigate-to-title="navigateToTitle"
          @set-task-date="setTaskDate"
          @delete-task="deleteTask"
          :active-calendar-task-id="activeCalendarTaskId"
          @set-active-calendar="setActiveCalendar"
          @delete-card="handleDeleteCard"
          @move-card="handleMoveCard"
          @update-task-show-date-mode="updateTaskShowDateMode"
          @clear-active-card="clearActiveCard"
      />
    </div>

    <NewTaskListDialog
        v-model="showNewListDialog"
        v-model:new-list-name="newListName"
        @confirm="createNewTaskList"
    />

    <TaskOptionsMenu
        v-if="showTaskOptions"
        :style="{ left: menuLeft + 'px', top: menuTop + 'px' }"
        @add-to-star="() => addTaskToStar(activeTaskListIndex, activeTaskIndex)"
        @add-deadline="() => addTaskDeadline(activeTaskListIndex, activeTaskIndex)"
        @add-subtask="() => addSubTask(activeTaskListIndex, activeTaskIndex)"
        @delete="() => deleteTask(activeTaskListIndex, activeTaskIndex)"
        @close="showTaskOptions = false"
    />

    <UserCard
        :show-user-card="showUserCard"
        @close-user-card="closeUserCard"
        @manage-account="handleManageAccount"
        @logout="handleLogout"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import TaskHeader from "../components/Task/TaskHeader.vue";
import TaskSidebar from "../components/Task/TaskSidebar.vue";
import TaskCardList from "../components/Task/TaskCardList.vue";
import NewTaskListDialog from "../components/Task/NewTaskListDialog.vue";
import TaskOptionsMenu from "../components/Task/TaskOptionsMenu.vue";
import UserCard from '@/components/Calendar/UserCard.vue'
import { useUserStore } from '@/store/user'
import { useTaskListStore } from '@/store/taskList'
import type { Task, TaskList } from '@/types/taskList'

const router = useRouter()
const userStore = useUserStore()
const taskListStore = useTaskListStore()

const sidebarCollapsed = ref(false)
const activeListIndex = ref(0)
const showNewListDialog = ref(false)
const newListName = ref('')
const isTaskListOpen = ref(false)
const showUserCard = ref(false)

const showTaskOptions = ref(false)
const activeTaskListIndex = ref(-1)
const activeTaskIndex = ref(-1)
const menuLeft = ref(0)
const menuTop = ref(0)
const activeCalendarTaskId = ref<string | null>(null)
const taskCardListRef = ref<HTMLElement | null>(null)

const taskLists = computed<TaskList[]>(() => taskListStore.taskLists)

const setActiveCalendar = (taskId: string | null) => {
  activeCalendarTaskId.value = taskId
}

const clearActiveCard = () => {
  activeListIndex.value = -1;
}

const handleCategoryClick = (index: number, event: MouseEvent) => {
  if ((event.target as HTMLElement).closest('.el-checkbox')) return
  const targetList = taskLists.value[index]
  if (!targetList || !targetList.visible) return
  activeListIndex.value = index
}

const handleVisibilityChange = async (index: number) => {
  const list = taskLists.value[index]
  if (!list) return

  const newVisible = !list.visible
  await taskListStore.updateTaskListAnimation(
      list.id,
      newVisible ? 'appearing' : 'disappearing',
      false
  )

  if (list.visible && activeListIndex.value === index) {
    activeListIndex.value = -1
  }

  if (newVisible) {
    setTimeout(async () => {
      await taskListStore.updateTaskListAnimation(list.id, 'appearing', true)
      setTimeout(async () => {
        await taskListStore.updateTaskListAnimation(list.id, 'idle', true)
        await taskListStore.toggleTaskListVisibility(list.id, newVisible)
      }, 300)
    }, 80)
  } else {
    setTimeout(async () => {
      await taskListStore.updateTaskListAnimation(list.id, 'idle', false)
      await taskListStore.toggleTaskListVisibility(list.id, newVisible)
    }, 300)
  }
}

const addNewTask = () => {
  if (activeListIndex.value >= 0 && activeListIndex.value < taskLists.value.length) {
    addTaskToList(activeListIndex.value)
  }
}

// 向列表添加任务（修复自动定位新任务）
const addTaskToList = async (listIndex: number) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return

  // 记录添加前的任务数量
  const prevTaskCount = targetList.tasks.length

  // 通过Store添加任务（date为空时使用'today'，确保能同步到日历）
  await taskListStore.addTask(targetList.id, {
    title: '新任务',
    description: '添加任务描述',
    date: 'today', // 默认为今天，确保能同步到日历
    showDateAsText: false,
    completed: false,
    editingTitle: false,
    editingDesc: false,
    starred: false
  })

  await nextTick()

  const updatedList = taskLists.value[listIndex]
  if (!updatedList || updatedList.tasks.length <= prevTaskCount) return

  scrollToNewTask(updatedList.id)
}

const scrollToNewTask = (listId: string) => {
  const list = taskLists.value.find(item => item.id === listId)
  if (!list || list.tasks.length === 0) return

  const newTask = list.tasks[list.tasks.length - 1]
  if (!newTask) return

  const newTaskElement = document.querySelector(`.task-card[data-list-id="${listId}"] .task-item:last-child`)
  if (newTaskElement) {
    newTaskElement.scrollIntoView({
      behavior: 'smooth',
      block: 'nearest'
    })

    setTimeout(() => {
      const titleElement = newTaskElement.querySelector('.task-title') as HTMLElement
      if (titleElement) {
        titleElement.click()
      }
    }, 300)
  }
}

const createNewTaskList = async () => {
  const name = newListName.value.trim() || '未命名列表'
  await taskListStore.createTaskList(name)
  newListName.value = ''
  showNewListDialog.value = false

  nextTick(() => {
    activeListIndex.value = taskLists.value.length - 1
    if (taskCardListRef.value) {
      (taskCardListRef.value as any).scrollToCard(activeListIndex.value)
    }
  })
}

const toggleTaskOptions = (listIndex: number, taskIndex: number, event: MouseEvent) => {
  if (showTaskOptions.value && activeTaskListIndex.value === listIndex && activeTaskIndex.value === taskIndex) {
    showTaskOptions.value = false
    return
  }
  const targetList = taskLists.value[listIndex]
  if (!targetList || !targetList.tasks[taskIndex]) return
  activeTaskListIndex.value = listIndex
  activeTaskIndex.value = taskIndex
  const buttonRect = (event.target as HTMLElement).getBoundingClientRect()
  menuLeft.value = buttonRect.right + window.scrollX + 5
  menuTop.value = buttonRect.bottom + window.scrollY + 5
  showTaskOptions.value = true
}

const handleCardClick = (listIndex: number) => {
  activeListIndex.value = listIndex
}

const startEditingListName = (listIndex: number) => {
  taskLists.value.forEach(list => list.editingName = false)
  const targetList = taskLists.value[listIndex]
  if (targetList) targetList.editingName = true
}

const saveListName = (listIndex: number, newName: string) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const trimmedName = newName.trim() || '未命名列表'
  taskListStore.updateTaskListName(targetList.id, trimmedName)
}

const showListOptionsMenu = (listIndex: number) => {
  console.log('打开列表选项菜单', listIndex)
}

// 核心修改：通过store更新completed状态并存储
const handleTaskComplete = async (listIndex: number, taskIndex: number, checked: boolean) => {
  const targetList = taskLists.value[listIndex];
  if (!targetList) {
    console.error('handleTaskComplete: 任务列表不存在, listIndex:', listIndex);
    return;
  }
  const task = targetList.tasks[taskIndex];
  if (!task) {
    console.error('handleTaskComplete: 任务不存在, taskIndex:', taskIndex, 'listIndex:', listIndex);
    return;
  }

  console.log('handleTaskComplete: 开始更新任务状态', {
    taskId: task.id,
    taskTitle: task.title,
    oldStatus: task.completed,
    newStatus: checked,
    listId: targetList.id,
    listName: targetList.name
  });

  // 1. 通过store更新任务的completed状态（会自动存储到localStorage）
  await taskListStore.updateTask(targetList.id, task.id, { completed: checked });

  // 验证状态是否已更新
  const updatedList = taskLists.value[listIndex];
  const updatedTask = updatedList?.tasks.find(t => t.id === task.id);
  console.log('handleTaskComplete: 状态更新后', {
    taskId: task.id,
    newStatus: updatedTask?.completed,
    success: updatedTask?.completed === checked
  });

  // 2. 处理任务位置移动（保持原有逻辑）
  if (checked) {
    await taskListStore.moveTaskToEnd(targetList.id, task.id);
  } else {
    await taskListStore.moveTaskToStart(targetList.id, task.id);
  }
};

const startEditing = (listIndex: number, taskIndex: number, type: 'title' | 'desc') => {
  taskLists.value.forEach(list => {
    list.editingName = false
    list.tasks.forEach(t => {
      t.editingTitle = false
      t.editingDesc = false
    })
  })
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (!task) return

  if (type === 'title') {
    task.editingTitle = true
  } else {
    task.editingDesc = true
  }
  taskListStore.updateTask(targetList.id, task.id, {
    editingTitle: type === 'title',
    editingDesc: type === 'desc'
  })
}

const saveEditing = (listIndex: number, taskIndex: number, type: 'title' | 'desc', event: Event) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (!task) return
  const target = event.target as HTMLElement
  const content = target.innerText.trim()

  if (type === 'title') {
    taskListStore.updateTask(targetList.id, task.id, {
      title: content || '未命名任务',
      editingTitle: false
    })
  } else {
    taskListStore.updateTask(targetList.id, task.id, {
      description: content || '无描述',
      editingDesc: false
    })
  }
}

const handleTitleEnter = (listIndex: number, taskIndex: number) => {
  navigateToDesc(listIndex, taskIndex)
}

const navigateToDesc = (listIndex: number, taskIndex: number) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (!task) return

  taskListStore.updateTask(targetList.id, task.id, {
    editingTitle: false,
    editingDesc: true
  })
}

const navigateToTitle = (listIndex: number, taskIndex: number) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (!task) return

  taskListStore.updateTask(targetList.id, task.id, {
    editingTitle: true,
    editingDesc: false
  })
}

const setTaskDate = (listIndex: number, taskIndex: number, date: 'today' | 'tomorrow' | string) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (task) {
    taskListStore.updateTask(targetList.id, task.id, { date })
  }
}

const addTaskToStar = (listIndex: number, taskIndex: number) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (task) {
    taskListStore.updateTask(targetList.id, task.id, {
      starred: !task.starred
    })
  }
}

const addTaskDeadline = (listIndex: number, taskIndex: number) => {
  ElMessage.info('添加截止时间功能待实现')
}

const addSubTask = (listIndex: number, taskIndex: number) => {
  ElMessage.info('添加子任务功能待实现')
}

const deleteTask = (listIndex: number, taskIndex: number) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (task) {
    taskListStore.deleteTask(targetList.id, task.id)
    showTaskOptions.value = false
  }
}

const goCalendarPage = () => router.push('/calendar')
const goTaskPage = () => router.push('/task')

const handleDeleteCard = async (listIndex: number) => {
  const list = taskLists.value[listIndex];
  if (!list || !list.visible) return;

  await handleVisibilityChange(listIndex);

  setTimeout(async () => {
    await taskListStore.deleteTaskList(list.id);

    if (activeListIndex.value === listIndex) {
      activeListIndex.value = -1;
    }
  }, 300);
};

const handleMoveCard = (listIndex: number) => {
  ElMessage.info('移动任务项功能待实现')
}

const showUserMenu = () => {
  showUserCard.value = true
}

const closeUserCard = () => {
  showUserCard.value = false
}

const handleManageAccount = () => {
  ElMessage.info('管理账号')
  closeUserCard()
}

const handleLogout = () => {
  userStore.logout()
  closeUserCard()
  router.push('/login')
}

const handleClickOutside = (event: MouseEvent) => {
  const userCard = document.querySelector('.user-card')
  const userAvatar = document.querySelector('.user-avatar')

  if (
      showUserCard.value &&
      userCard &&
      !userCard.contains(event.target as Node) &&
      userAvatar &&
      !userAvatar.contains(event.target as Node)
  ) {
    closeUserCard()
  }
}

const updateTaskShowDateMode = async (listIndex: number, taskIndex: number, showAsText: boolean) => {
  const targetList = taskLists.value[listIndex]
  if (!targetList) return
  const task = targetList.tasks[taskIndex]
  if (task) {
    await taskListStore.updateTask(targetList.id, task.id, {
      showDateAsText: showAsText,
      updatedAt: new Date().toISOString()
    })
  }
}

watch(
    () => taskLists.value.map(l => l.visible),
    () => {
      nextTick(() => {
        const currentList = taskLists.value[activeListIndex.value]
        if (!currentList || !currentList.visible) {
          activeListIndex.value = -1
        }
      })
    },
    { deep: true }
)

onMounted(async () => {
  await taskListStore.init()
  document.addEventListener('click', handleClickOutside)

  document.addEventListener('click', (e) => {
    const target = e.target as HTMLElement
    if (!target.closest('.card-title') && !target.closest('.task-content')) {
      taskLists.value.forEach(list => {
        list.editingName = false
        list.tasks.forEach(task => {
          task.editingTitle = false
          task.editingDesc = false
        })
      })
    }
    if (!target.closest('.task-option') && !target.closest('.task-options-menu')) {
      showTaskOptions.value = false
    }
  })
})
</script>

<style scoped>
.task-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  overflow: hidden;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}
</style>